package com.gin.pixiv.callback

import com.gin.pixiv.response.PixivResponse
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

/**
 * 回调
 * @author bx002
 * @since 2024/2/18 15:06
 */
abstract class PixivCallback<T> : Callback<PixivResponse<T>> {
    /**
     * 请求成功的处理
     */
    abstract fun onSuccess(body: T?)

    final override fun onResponse(
        call: Call<PixivResponse<T>>,
        response: Response<PixivResponse<T>>,
    ) {
        val rawRes = response.raw()
        if (rawRes.code != 200) {
            onError(rawRes.code, rawRes.message, call, response, rawRes);
            return;
        }
        val resBody = response.body()!!
        if (resBody.error!!) {
            throw RuntimeException(resBody.message)
        } else {
            onSuccess(resBody.body);
        }
    }

    open fun onError(
        code: Int,
        message: String,
        call: Call<PixivResponse<T>>,
        response: Response<PixivResponse<T>>,
        rawRes: okhttp3.Response,
    ) {
        throw RuntimeException("Error code: ${code}; message: ${message} ")
    }

    override fun onFailure(call: Call<PixivResponse<T>>, t: Throwable) {
        t.printStackTrace()
    }
}